//
//  SegmentAnalyticsService.swift
//  Runner
//
//  Created by SZTeam on 27/2/2024.
//

import Foundation
import ESDSegmentAnalytics

public class SegmentAnalyticsService {
    
    // 和 Flutter 调用的方法名同步
    enum MethodType: String {
        case initial
        case identify
        case track
        case screen
        case group
    }
    
    static let shared = SegmentAnalyticsService()
    var analytics: ObjCAnalytics? = nil
    
    func setup(_ writeKey: String) {
        let configuration = ObjCConfiguration(writeKey: writeKey)
        configuration.trackApplicationLifecycleEvents = true
        configuration.flushAt = 3
        configuration.flushInterval = 10
        analytics = ObjCAnalytics(configuration: configuration)
    }
}

extension SegmentAnalyticsService {
    public func execute(methodName: String, arguments: Any?) -> Bool {
        guard let parameters = arguments as? [String: Any] else {
            return false
        }
        guard let type: MethodType = MethodType(rawValue: methodName.lowercased()) else {
            return false
        }
        
        switch type {
        case .initial:
            guard let key = parameters["segment_write_key"] as? String else {
                return true
            }
            setup(key)
        case .identify:
            guard let userId = parameters["user_id"] as? String else {
                return true
            }
            let traits = parameters["params"] as? [String: Any]
            analytics?.identify(userId: userId, traits: traits)
        case .track:
            guard let name = parameters["name"] as? String else {
                return true
            }
            let properties = parameters["params"] as? [String: Any]
            analytics?.track(name: name, properties: properties)
        case .screen:
            guard let title = parameters["title"] as? String else {
                return true
            }
            let category = parameters["category"] as? String
            let properties = parameters["params"] as? [String: Any]
            analytics?.screen(title: title, category: category, properties: properties)
        case .group:
            guard let groupId = parameters["group_id"] as? String else {
                return true
            }
            let traits = parameters["params"] as? [String: Any]
            analytics?.group(groupId: groupId, traits: traits)
        }
        
        return true
    }
}
